#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/4/29 10:20
# @Author  : CHEN Wang
# @Site    :
# @File    : mail_tool.py
# @Software: PyCharm

"""
脚本说明: 邮件以及钉钉提醒模块
参考：https://www.runoob.com/python/python-email.html
     https://zhuanlan.zhihu.com/p/24180606
"""

import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse
import yagmail
from retrying import retry

monitor_param = {
    "email": {
        "identify": 1,
        "subject": None,
        "message": None,
        "CC": None,
        "file": None,
        # "sender": {"user": 'dxsl_researcher@163.com',
        #            "password": 'JXFSRTXHMQJJDTGC',
        #            "host": 'smtp.163.com'},
        "sender": {"user": 'tianzhiguanlizixun@163.com', "password": 'VMUXBIXRSTMBJYDW', "host": 'smtp.163.com'}
    }
}


def DataFrame_to_html(message: dict):
    """
    将pd.DataFrame数据传入html表中，并返回html代码

    :param dict message:{'估值':df}
    return str ht
    """
    # warning1 = '<h4 style="color:red;">字体放大 CTRL+SHILT+></h4>'
    # warning2 = '<h4 style="color:red;">字体缩小 CTRL+SHILT+<</h4>'
    body = ''
    for key, value in message.items():
        title = f'<h4 style="color:red;"><font size="8">{key}</font></h4>'
        setting = f'<table border="1" cellspacing="0" cellpadding="1" bordercolor="#00000" width="50%" style="word-wrap:break-word;">'
        df = message[key].copy()
        row = df.index
        col = df.columns
        th = ''
        for j in col:
            th += f'<th nowrap="nowrap"><nobr>{str(j)}</nobr></th>'
        heading = f'<tr>{th}</tr>'
        tr = ''
        for i in row:
            td = ''
            for j in col:
                if df[j][i] is None:
                    td += f'<td>&nbsp;</td>'
                else:
                    td += f'<td nowrap="nowrap"><nobr>{str(df[j][i])}</nobr></td>'
            tr += f'<tr>{td}</tr>'
        table = f'{tr}</table>'
        onetable = title + setting + heading + table
        body += onetable
    # html_message = f'<html><body>{warning1 + warning2 + body}</body></html>'
    html_message = f'<html><body>{body}</body></html>'
    return html_message


def figure_to_html(file_path):
    figure_html = yagmail.inline(file_path)
    return figure_html


class exceptionSimpleModel:
    @retry(stop_max_attempt_number=3)
    def except_main(self, outtype, monitor_param):
        # 单工具提醒：1-邮件提醒，2-钉钉提醒，等；
        # 多工具提醒：11-全部工具，12-等
        if outtype == 1:
            self.exception_email(**monitor_param)
        elif outtype == 2:
            self.dingmessage(**monitor_param)
        elif outtype == 11:
            self.exception_email(**monitor_param)
            self.dingmessage(**monitor_param)

    def exception_email(self, identify, subject, message, sender=None, receiver=None, CC=None, file=None):
        """

        :param int identify: 邮件标识：1-发送邮件，0-不发送
        :param str subject: 邮件主题
        :param str message: 邮件主体内容，如果换行，用多个单引号，如：contents = ['This is the body', 'hello,
        you are good!']
        :param dict sender: 数据类型：字典，例子：{user="user@126.com", password="1234", host='smtp.126.com'}
        注意：个人邮箱password是授权码，不是密码，目前默认邮箱是：腾讯企业邮箱
        :param str or list receiver: 收件人，单个收件人数据类型：字符串, 多个收件人数据类型：列表
        :param str or list CC: 抄送人，单个收件人数据类型：字符串, 多个收件人数据类型：列表
        :param list file: 附件，数据类型：列表
        :return:
            for example: exceptionSimple.exception_email(identify=1,  message='test', subject='aa')
                 sender, receiver:默认是系统参数

                 邮件内容：提供html格式，示例：
                 contents = [
                            "<h1 style='color:red'>一级标题</h1>",#可以是html语言
                            'beauty.jpg',#可以是文件,以附件形式发送
                            # yagmail.inline('beauty.jpg'),# 这样的话,图片会内嵌到正文
                            'hello world', #可以是普通文本
                            ]
        """

        if sender is None:
            sender = {"user": 'dxsl_researcher@163.com',
                      "password": 'JXFSRTXHMQJJDTGC',
                      "host": 'smtp.163.com'}
        if receiver is None:
            receiver = ['zjuvincent@163.com']

        if identify == 1:
            yagUesr = yagmail.SMTP(**sender)
            yagUesr.send(to=receiver, subject=subject, contents=message, cc=CC, attachments=file)
        elif identify == 0:
            pass
        print('邮件发送成功')


if __name__ == '__main__':
    import pandas as pd

    df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])
    message = DataFrame_to_html({'test': df})
    figure = figure_to_html(r'E:\指标测试-第四版\all_selected_strategy_signal-2022-01-18\综合信号-signal_backtest.png')

    exceptionSimple = exceptionSimpleModel()
    # 测试邮件
    emailParam = monitor_param["email"]
    emailParam["subject"] = "你好"
    # emailParam["message"] = [message, figure]
    emailParam["message"] = '呦呦，切克闹，优秀！'
    # emailParam["file"] = [r'E:\指标数据\all_ohlcv.csv']  # 添加附件
    emailParam["receiver"] = ['jeffzhangzhenda@hotmail.com', '1207804643@qq.com', '156730794@qq.com']
    exceptionSimple.except_main(1, emailParam)
